package eu.base.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class SelfishLineIterator implements TextLineIterator {

	RandomAccessFile rf;
	String encoding = "UTF-8";
	List<String> buffer = null;
	ListIterator<String> it = null;

	public SelfishLineIterator(File file, String encoding) {
		try {
			this.encoding = encoding;
			rf = new RandomAccessFile(file, "rw");
			buffer = new LinkedList<String>();
			TextOperator tr = new TextOperator(file);
			buffer.addAll(tr.readLines());
			it = buffer.listIterator();
			tr.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}


	@Override
	public boolean hasNext() {
		if (buffer != null)
			return it.hasNext();
		try {
			return rf.getFilePointer() < rf.length();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public String next() {
		if (buffer != null)
			return it.next();
		try {
			return rf.readLine();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public void remove() {
		if (buffer != null) {
			it.remove();
		}
		try {
			//
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean usingBuffer() {
		return buffer != null;
	}

	public void flushBuffer() {
		if (buffer != null) {
			try {
				rf.setLength(0);
				head();
				while (hasNext()) {
					rf.write((next() + (hasNext() ? "\r\n" : ""))
							.getBytes(encoding));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void head() {
		it = buffer.listIterator();
	}

	public void close() {
		flushBuffer();
	}

	@Override
	public boolean hasPrevious() {
		return it.hasPrevious();
	}

	@Override
	public String previous() {
		return it.previous();
	}

	@Override
	public int nextIndex() {
		return it.nextIndex();
	}

	@Override
	public int previousIndex() {
		return it.previousIndex();
	}

	@Override
	public void set(String e) {
		it.set(e);
	}

	@Override
	public void add(String e) {
		it.add(e);
	}
}
